$(function () {
    const token = sessionStorage.getItem('token');

    if (!token) {
        // 假设登录页面的 URL 是 /login
        alert('请先登录！');
        window.location.href = 'login.html';
        return;
    }
})


// 字数统计
const commentText = document.getElementById('commentText');
const charCount = document.getElementById('charCount');
commentText.addEventListener('input', () => {
    charCount.textContent = `${commentText.value.length}/100`;
});

// 保存各个评分项的分数
const ratings = {
    设施: 0,
    服务: 0,
    卫生: 0,
    位置: 0,
    餐饮: 0
};

// 星级评分功能
document.querySelectorAll('.stars-group').forEach(group => {
    const stars = group.querySelectorAll('.stars');
    const ratingScore = group.querySelector('.rating-score'); // 获取评分显示元素
    const label = group.previousElementSibling.textContent; // 获取评分项的标签（如 设施、服务等）

    stars.forEach((star, index) => {
        star.addEventListener('click', () => {
            const rating = index + 1;
            group.dataset.rating = rating;
            updateStars(group, rating);
            ratingScore.textContent = rating; // 更新评分显示
            ratings[label] = rating; // 更新对应项的评分

            updateTotalRating(); // 更新总评分
        });
    });
});

function updateStars(group, rating) {
    const stars = group.querySelectorAll('.stars');
    stars.forEach((star, index) => {
        star.classList.toggle('selected', index < rating);
    });
}

// 更新总评分
function updateTotalRating() {
    const totalScore = Object.values(ratings).reduce((sum, score) => sum + score, 0);
    const average = totalScore / 5; // 总评分为所有评分的和除以5
    document.getElementById('totalRating').textContent = average.toFixed(1); // 显示总评分，保留一位小数
}

// 出行身份按钮高亮
const identityButtons = document.querySelectorAll('.identity-buttons button');
identityButtons.forEach(button => {
    button.addEventListener('click', () => {
        identityButtons.forEach(btn => btn.classList.remove('selected'));
        button.classList.add('selected');
    });
});

// 图片上传预览
function previewImages() {
    const imageUpload = document.getElementById('imageUpload');
    const imagePreview = document.getElementById('imagePreview');
    imagePreview.innerHTML = '';  // 清空之前的预览

    const files = imageUpload.files;
    if (files.length > 3) {
        alert('最多上传3张图片');
        imageUpload.value = '';
        return;
    }

    Array.from(files).forEach(file => {
        const reader = new FileReader();
        reader.onload = (e) => {
            const img = document.createElement('img');
            img.src = e.target.result;
            imagePreview.appendChild(img);
        };
        reader.readAsDataURL(file);
    });
}

// 表单验证与提交
function submitReview() {
    const commentError = document.getElementById('commentError');

    if (!commentText.value.trim()) {
        commentError.style.display = 'block';
    } else {
        commentError.style.display = 'none';
        alert('点评提交成功！');
        // 执行提交操作，例如AJAX发送数据
    }
}
const urlParams = new URLSearchParams(window.location.search);

const orderId = urlParams.get('orderId');  // 获取 flag 参数的值
const hotelName = urlParams.get('hotel_name');
$(function () {

    console.log(hotelName);


    document.getElementById('hotelName').innerText = hotelName
})

document.getElementById("customUploadBtn").addEventListener("click", function () {
    document.getElementById("fileUploadImages").click(); // 触发文件选择
});


$('#fileUploadImages').on('change', function (e) {
    e.preventDefault(); // 阻止默认的提交行为


    const files = e.target.files;
    const formData = new FormData();

    if (files.length > 3) {
        alert('请上传规定数量的评价图片！');
        return;
    }

    // 将文件添加到 FormData 中
    for (let i = 0; i < files.length; i++) {
        formData.append('file', files[i]);
    }

    // 添加文件名称字段
    formData.append('files', 'hotels/images/access');

    $.ajax({
        url: 'http://localhost:8080/file/upload',
        Headers: sessionStorage.getItem('token'),
        type: "post",
        data: formData,
        processData: false,   // 需要禁用 jQuery 的自动处理
        contentType: false,   // 让浏览器自动设置 Content-Type 头
        success: function (rs) {
            if (rs.code === 2001) {
                const hrefs = rs.t
                let hrefString = '';  // 使用 let 而不是 const
                if (hrefs.length > 0) {
                    hrefString = hrefs.join(';');  // 重新赋值
                } else {
                    hrefString = hrefs[0];  // 重新赋值
                }
                // 将拼接后的字符串设置到隐藏的 input 元素中
                document.getElementById('assessImg').value = hrefString;
                const previewContainer = document.getElementById('imagePreview');
                previewContainer.innerHTML = ''; // 清空现有的预览
                hrefs.forEach(href => {
                    const img = document.createElement('img');
                    img.src = href;
                    img.style.maxWidth = '100px'; // 可调整图片的显示大小
                    img.style.marginRight = '10px'; // 可调整图片之间的间隔
                    previewContainer.appendChild(img);
                })
            }
        },
        error: function (xhr, status, error) {
            console.error("Error:", status, error);
        }

    })

})

$('#access_btn').on('click', function (e) {
    e.preventDefault();
    const score = $('#totalRating').text();
    const accessInfo = $('#commentText').val();
    const accessImage = $('#assessImg').val();
    const dueId = orderId;
    console.log(score);

    if (!score) {
        alert("评分不能为空！");
        return;
    }

    if (!accessInfo) {
        alert("评论内容不能为空！");
        return;
    }
    if (!accessImage) {
        alert('请上传酒店图片');
        return
    }

    const formData = {
        score,
        accessInfo,
        accessImage,
        dueId
    }
    $.ajax({
        url: 'http://localhost:8080/assess/save',
        type: "post",
        headers: {
            'token': sessionStorage.getItem('token')
        },
        contentType: 'application/json',  // 确保请求头是 application/json
        data: JSON.stringify(formData),
        success: function (rs) {
            if (rs.code === 2001) {
                alert('评价成功！')
                window.location.href = 'Me.html'
            } else {
                alert('评价失败，请重试或联系客服！')
            }
        },
        error: function (xhr, status, error) {
            console.error("Error:", status, error);
        }
    })

})